package com.edwardyk.java.tools;

import java.util.ArrayList;


public class YKTaskUtil {

    public interface TaskUtilCallBack {

        void doNext();
    }
    private class TaskUtilModel {
        private TaskUtilCallBack callBack;
        private int sort;
    }

    private final ArrayList<TaskUtilModel> taskList = new ArrayList<>();
    private int currentIndex = 0;
    private int saveIndex = 0;

    public YKTaskUtil() {}
    public void addTask(int sort, TaskUtilCallBack callBack) {
        if (callBack != null) {
            TaskUtilModel utilModel = new TaskUtilModel();
            utilModel.callBack = callBack;
            utilModel.sort = sort;

            this.taskList.add(utilModel);

            for (int i = 1; i < this.taskList.size(); i++) {
                for (int j = i; j > 0 ; j--) {
                    if (this.taskList.get(j).sort > this.taskList.get(j-1).sort) {
                        TaskUtilModel model  = this.taskList.get(j);
                        this.taskList.set(j,this.taskList.get(j-1));
                        this.taskList.set(j-1,model);
                    }
                }
            }
        }
    }

    public void executeFirstTask() {
        this.currentIndex = 0;
        this.saveIndex = 0;
        nextTask();
    }

    public void nextTask() {
        if (this.currentIndex > (this.taskList.size() - 1)) {
            return;
        }
        TaskUtilModel utilModel = this.taskList.get(this.currentIndex);
        try {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    utilModel.callBack.doNext();
                }
            }).start();


            this.saveIndex = this.currentIndex;
            this.currentIndex = this.currentIndex + 1;

        } catch (Exception ignored) {
            throw new RuntimeException(ignored);
        }


    }

    public void rollBackLastTask() {
        if (this.currentIndex <= 0) {
            return;
        }
        this.currentIndex = this.saveIndex;
    }

    public void clear() {
        this.taskList.clear();
        this.currentIndex = 0;
        this.saveIndex = 0;
    }
}

